<template>
  <a-modal
    :title="showTitleName"
    :width="1200"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :align-center="true"
    :unmount-on-close="true"
    :mask-closable="false"
    ok-text="确认"
    @ok="handleOk"
    @cancel="handleCancel"
    :body-style="{ 'max-height': '700px', overflow: 'auto' }"
  >
    <variable-selection
      :var-options="nameList"
      v-if="visible && varVisible"
    ></variable-selection>
    <a-spin :spinning="confirmLoading">
      <a-row
        class="form-item-height table-page-search-wrapper"
        :gutter="[16, 0]"
      >
        <a-col :md="12" :sm="24">
          入参：
          <a-form
            ref="infoViews"
            :rules="rules"
            :model="formModel"
            label-align="right"
          >
            <a-col
              v-for="item in formModel.customFormList"
              :key="item.foreignKey"
            >
              <template>
                <a-form-item :label="item.foreignKey">
                  <a-select
                    v-model="item.handFilled"
                    style="width: 33%; margin-right: 2%"
                  >
                    <a-option value="">选择字段</a-option>
                    <a-option value="input">手填</a-option>
                    <a-option value="editor">富文本</a-option>
                    <a-option value="hide">隐藏</a-option>
                    <a-option value="disabled">禁用</a-option>
                  </a-select>
                  <a-textarea
                    v-if="item.handFilled === 'editor'"
                    v-model="item.columnKey"
                    :auto-size="{ minRows: 4 }"
                    placeholder="请输入内容"
                    style="width: 60%"
                  />
                  <a-input
                    v-else-if="
                      item.handFilled === 'input' && item.handFilled !== 'hide'
                    "
                    v-model="item.columnKey"
                    style="width: 60%"
                  ></a-input>
                  <a-select
                    v-else
                    v-model="item.columnKey"
                    :allow-clear="true"
                    style="width: 60%"
                  >
                    <a-option
                      v-for="nameObj in nameList"
                      :key="nameObj.value"
                      :value="nameObj.value"
                      >{{ nameObj.label }}
                    </a-option>
                  </a-select>
                  <!--                  <a-checkbox v-model="item.disabled">禁用</a-checkbox>-->
                </a-form-item>
              </template>
            </a-col>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          出参：
          <a-col v-for="(value, key) in outputFormList" :key="key">
            <template>{{ key }}</template>
          </a-col>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<script>
import _ from "lodash";
import VariableSelection from "@/components/Form/Custom/VariableSelection.vue";

export default {
  name: "CustomBtnModal",
  components: { VariableSelection },
  props: {
    dataObj: {
      type: Object,
      default: () => {},
    },
    plugObj: {
      type: Object,
      default: () => {},
    },
    nameList: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    showTitleName() {
      return this.foreignKeyExists
        ? this.plugObj.plugName
        : this.modalList?.plugName;
    },
  },
  watch: {
    visible(newVal) {
      setTimeout(() => {
        this.varVisible = newVal; // 给变量按钮一个缓冲显示的时间
      }, 400);
    },
  },
  data() {
    return {
      formModel: {
        customFormList: [],
      },
      varVisible: false,
      visible: false,
      confirmLoading: false,
      wrapperCol: { span: 14 },
      labelCol: { span: 10 },
      modalList: [], // 新增时插件接口全部数据
      curIndex: null, // 当前索引
      editList: {}, // 编辑时的后台格式数据
      foreignKeyExists: false, // 是否有编辑的数据
      rules: {},
      outputFormList: {}, // 出参数据
      inputParamObj: {}, // 入参
      isPlugEdit: false, // 是否是编辑
      isNoCodeEdit: false, // 无代码是否是编辑
    };
  },
  created() {},
  methods: {
    async open(record, editRecord, index) {
      console.info("```open", editRecord);
      console.info("````", record[0]);
      const { inputParam, outputParam } = record[0].plugParamIODTO;
      const { eventColumnMappingAddDTOList, columnPlugAddDTOList } = editRecord;
      this.isPlugEdit =
        (eventColumnMappingAddDTOList && eventColumnMappingAddDTOList.length) ||
        false;
      const formMappingList = eventColumnMappingAddDTOList;
      this.isNoCodeEdit =
        (columnPlugAddDTOList && columnPlugAddDTOList.length) || false;
      const noCodeMappingList = columnPlugAddDTOList;
      const mappingList = Object.keys(inputParam).map((key) => {
        if (["noCodeAdd", "noCodeEdit"].includes(this.dataObj.mode)) {
          const noCodeMapping =
            noCodeMappingList.find((item) => item.plugKey === key) || {};
          return {
            ...noCodeMapping,
            columnKey: this.isNoCodeEdit
              ? noCodeMapping.plugColumn || noCodeMapping.expression
              : "",
            foreignKey: key,
            handFilled: noCodeMapping.handFilled || "",
          };
        } else {
          const formMapping =
            formMappingList.find((item) => item.foreignKey === key) || {};
          return {
            ...formMapping,
            columnKey: this.isPlugEdit
              ? formMapping.columnKey || formMapping.expression
              : "",
            foreignKey: key,
            handFilled: formMapping.handFilled || "",
          };
        }
      });
      this.formModel.customFormList = _.cloneDeep(mappingList);
      this.outputFormList = outputParam;
      this.inputParamObj = inputParam;
      this.curIndex = index;
      this.visible = true;
    },
    // 弹框确认
    handleOk() {
      this.$refs.infoViews.validate(async (valid) => {
        if (valid) {
          if (["add", "edit"].includes(this.dataObj.mode)) {
            const eventColumnList = this.formModel.customFormList.map(
              (item) => {
                const isExpression = this.nameList.find(
                  (e) => e.value === item.columnKey
                )?.isExpression;
                return {
                  columnKey:
                    !isExpression &&
                    !["editor", "input"].includes(item.handFilled)
                      ? item.columnKey || ""
                      : "",
                  foreignKey: item.foreignKey,
                  expression:
                    isExpression || !["hide"].includes(item.handFilled)
                      ? item.columnKey || ""
                      : "",
                  handFilled: item.handFilled || "",
                  // eventId: this.plugObj.plugValue
                };
              }
            );
            this.dataObj.buttonData[
              this.curIndex
            ].eventColumnMappingAddDTOList = eventColumnList;
          } else {
            // 无代码
            const noCodeColumnList = this.formModel.customFormList.map(
              (item) => ({
                plugColumn: item.columnKey || "",
                plugKey: item.foreignKey,
                plugId: this.plugObj.plugValue,
                plugExecType: "exec",
                plugType: 1,
                columnType: 0,
              })
            );
            this.dataObj.buttonData[this.curIndex].columnPlugAddDTOList =
              noCodeColumnList;
            // 出参数据
            const noCodeOutputList = Object.keys(this.outputFormList).map(
              (key) => ({
                outputKey: key,
                outputType: 0,
              })
            );
            this.dataObj.buttonData[this.curIndex].columnOutputAddDTOList =
              noCodeOutputList;
            const noCodeFormExecList = {
              content: "",
              formExecAddDTO: {
                execParam: Object.keys(this.inputParamObj)
                  .map((item) => item)
                  .join(","),
                execType: this.dataObj.basicData.appType,
                execName: this.plugObj.plugValue,
              },
              type: this.dataObj.basicData.appType,
            };
            this.dataObj.buttonData[this.curIndex].formExecOpLoadFileDTO =
              noCodeFormExecList;
          }

          console.info("全部按钮信息", this.dataObj.buttonData);
          this.handleCancel();
          this.$emit("ok", this.formModel.customFormList);
          this.formModel = { customFormList: [] };
        }
      });
    },
    handleCancel() {
      this.$refs.infoViews.clearValidate();
      this.visible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.time-block {
  display: flex;
}

.form-item-height.table-page-search-wrapper {
  /deep/ .ant-form-inline .ant-form-item .ant-form-item-control {
    height: auto;
  }
}
/* 富文本样式 */
/deep/ .ql-container {
  height: 200px;
  width: 100%;
}
</style>
